package com.hitomi.refresh.view;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.app.Context;


/**
 * Created by Hitomis on 2016/3/9.
 * email:196425254@qq.com
 */
abstract class FunGameView extends Component implements Component.DrawTask, Component.EstimateSizeListener {
    static final int STATUS_GAME_PREPAR = 0;

    static final int STATUS_GAME_PLAY = 1;

    static final int STATUS_GAME_OVER = 2;

    static final int STATUS_GAME_FINISHED = 3;

    /**
     * 分割线默认宽度大小
     */
    static final float DIVIDING_LINE_SIZE = 1.f;

    /**
     * 控件高度占屏幕高度比率
     */
    static final float VIEW_HEIGHT_RATIO = .161f;

    /**
     * 图像画笔
     */
    protected Paint mPaint;

    /**
     * 文字画笔
     */
    protected Paint textPaint;

    /**
     * 移动控制器的距离
     */
    protected float controllerPosition;

    /**
     * 控制器的大小
     */
    protected int controllerSize;

    /**
     * 屏幕宽度
     */
    protected int screenWidth;

    /**
     * 屏幕高度
     */
    protected int screenHeight;

    /**
     * 游戏状态
     */
    protected int status = STATUS_GAME_PREPAR;

    /**
     * 左边物体的颜色
     */
    protected Color lModelColor;

    /**
     * 右边物体的颜色
     */
    protected Color rModelColor;

    /**
     * 中间小球的颜色
     */
    protected Color mModelColor;
    private String textGameOver;
    private String textLoading;
    private String textLoadingFinished;

    FunGameView(Context context, AttrSet attrSet, int resId) {
        super(context, attrSet, resId);
        init(context, attrSet);
    }

    FunGameView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init(context, attrSet);
    }


    private void init(Context context, AttrSet attrSet) {
        if (attrSet != null && attrSet.getAttr(Styleable.LEFT_MODEL_COLOR).isPresent()) {
            lModelColor = attrSet.getAttr(Styleable.LEFT_MODEL_COLOR).get().getColorValue();
        } else {
            lModelColor = new Color(Color.rgb(0, 0, 0));
        }
        if (attrSet != null && attrSet.getAttr(Styleable.MIDDLE_MODEL_COLOR).isPresent()) {
            mModelColor = attrSet.getAttr(Styleable.MIDDLE_MODEL_COLOR).get().getColorValue();
        } else {
            mModelColor = Color.BLACK;
        }
        if (attrSet != null && attrSet.getAttr(Styleable.RIGHT_MODEL_COLOR).isPresent()) {
            rModelColor = attrSet.getAttr(Styleable.RIGHT_MODEL_COLOR).get().getColorValue();
        } else {
            rModelColor = new Color(Color.getIntColor("#A5A5A5"));
        }

        initBaseTools();
        initBaseConfigParams(context);
        initConcreteView();
        setEstimateSizeListener(this);
        addDrawTask(this);
    }

    /**
     * 初始化画笔
     */
    protected void initBaseTools() {
        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setColor(new Color(Color.getIntColor("#C1C2C2")));

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(1.f);
    }

    /**
     * 初始化数据
     *
     * @param context 上下文
     */
    protected void initBaseConfigParams(Context context) {
        controllerPosition = DIVIDING_LINE_SIZE;
        int scale = getResourceManager().getDeviceCapability().screenDensity / 160;
        screenWidth = getResourceManager().getDeviceCapability().width * scale;
        screenHeight = getResourceManager().getDeviceCapability().height * scale;
    }

    /**
     * 初始化view
     */
    protected abstract void initConcreteView();

    /**
     * 绘画
     *
     * @param canvas 画布
     */
    protected abstract void drawGame(Canvas canvas);

    /**
     * 重置配置
     */
    protected abstract void resetConfigParams();

    /**
     * 绘制分割线
     *
     * @param canvas 默认画布
     */
    private void drawBoundary(Canvas canvas) {
        mPaint.setColor(new Color(Color.getIntColor("#606060")));
        canvas.drawLine(0, 0, screenWidth, 0, mPaint);
        canvas.drawLine(0, getEstimatedHeight(), screenWidth, getEstimatedHeight(), mPaint);
    }

    @Override
    public boolean onEstimateSize(int i, int i1) {
        setEstimatedSize(EstimateSpec.getSizeWithMode(screenWidth, EstimateSpec.PRECISE),
                EstimateSpec.getSizeWithMode((int) (screenHeight * VIEW_HEIGHT_RATIO), EstimateSpec.PRECISE));
        return true;
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        drawBoundary(canvas);
        drawText(canvas);
        drawGame(canvas);
    }


    /**
     * 绘制文字内容
     *
     * @param canvas 默认画布
     */
    private void drawText(Canvas canvas) {
        switch (status) {
            case STATUS_GAME_PREPAR:
            case STATUS_GAME_PLAY:
                textPaint.setTextSize(50);
                promptText(canvas, textLoading);
                break;
            case STATUS_GAME_FINISHED:
                textPaint.setTextSize(40);
                promptText(canvas, textLoadingFinished);
                break;
            case STATUS_GAME_OVER:
                textPaint.setTextSize(50);
                promptText(canvas, textGameOver);
                break;
        }
    }

    /**
     * 提示文字信息
     *
     * @param canvas 默认画布
     * @param text   相关文字字符串
     */
    private void promptText(Canvas canvas, String text) {
        float textX = (getWidth() - textPaint.measureText(text)) * .5f;
        float textY = getHeight() * .5f - (textPaint.ascent() + textPaint.descent()) * .5f;
        canvas.drawText(textPaint, text, textX, textY);
    }


    /**
     * 移动控制器（控制器对象为具体控件中的右边图像模型）
     *
     * @param distance 移动的距离
     */
    public void moveController(float distance) {
        float maxDistance = (getEstimatedHeight() - 2 * DIVIDING_LINE_SIZE - controllerSize);

        if (distance > maxDistance) {
            distance = maxDistance;
        }
        controllerPosition = distance;
        postInvalidate();
    }

    /**
     * 移动控制器到起点位置
     *
     * @param duration 用时
     */
    public void moveController2StartPoint(long duration) {
        AnimatorValue moveAnimator = new AnimatorValue();
        moveAnimator.setDuration(duration);
        moveAnimator.setCurveType(Animator.CurveType.ACCELERATE_DECELERATE);
        moveAnimator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {
                controllerPosition = v * (DIVIDING_LINE_SIZE - controllerPosition);
                postInvalidate();
            }
        });
        moveAnimator.start();
    }

    /**
     * 更新当前控件状态
     *
     * @param status 状态码
     */
    public void postStatus(int status) {
        this.status = status;
        if (status == STATUS_GAME_PREPAR) {
            resetConfigParams();
        }
        postInvalidate();
    }

    private void postInvalidate() {
        mContext.getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                invalidate();
            }
        });
    }


    /**
     * 获取当前控件状态
     *
     * @return 当前状态
     */
    public int getCurrStatus() {
        return status;
    }

    public String getTextGameOver() {
        return textGameOver;
    }

    public void setTextGameOver(String textGameOver) {
        this.textGameOver = textGameOver;
    }

    public String getTextLoading() {
        return textLoading;
    }

    public void setTextLoading(String textLoading) {
        this.textLoading = textLoading;
    }

    public String getTextLoadingFinished() {
        return textLoadingFinished;
    }

    public void setTextLoadingFinished(String textLoadingFinished) {
        this.textLoadingFinished = textLoadingFinished;
    }


}
